from flask import Flask, request, jsonify
import requests
import os
import urllib.parse
import re
from pathlib import Path

app = Flask(__name__)

# 创建保存文件的目录
SAVE_DIR = '@excle-import'
os.makedirs(SAVE_DIR, exist_ok=True)

@app.route('/webhook', methods=['POST'])
def webhook():
    # 接收webhook传来的JSON数据
    data = request.json
    
    # 存储接收到的链接
    received_link = data.get('链接', '')
    
    # 打印链接(用于调试)
    print(f"接收到的链接: {received_link}")
    
    # 下载链接中的文件
    if received_link:
        try:
            # 修改链接格式 - 将qingflow.com链接转换为file-prod.qingflow.com链接
            # 提取关键部分参数
            if "qingflow.com/api/storage/file" in received_link:
                # 使用正则表达式从原始URL中提取关键部分
                match = re.search(r'documents/data/invite/(.*?)/(.*?)\.pdf', received_link)
                if match:
                    folder_id = match.group(1)
                    file_id = match.group(2)
                    
                    # 由于无法直接使用原始链接，使用固定的URL格式构建新链接
                    # 注意：这个链接可能有时效性，实际应用中可能需要获取动态签名
                    modified_link = f"https://file-prod.qingflow.com/documents/data/invite/{folder_id}/{file_id}.pdf"
                    print(f"已修改链接为: {modified_link}")
                else:
                    modified_link = received_link
            else:
                modified_link = received_link
            
            # 从URL中提取文件名
            parsed_url = urllib.parse.urlparse(modified_link)
            path_parts = parsed_url.path.split('/')
            original_filename = path_parts[-1] if path_parts else 'downloaded_file'
            
            # 设置请求头，模拟浏览器请求，包含token和其他必要头信息
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0',
                'Accept': 'application/json, text/plain, */*',
                'Accept-Language': 'zh-CN;q=1,en;q=0.9',
                'Origin': 'https://qingflow.com',
                'Referer': 'https://qingflow.com/',
                'token': 'caf211a7-738d-48ea-94a5-9e28ac34a881',  # 实际使用中可能需要动态获取
                'wsid': '635964',  # 实际使用中可能需要动态获取
            }
            
            # 创建会话对象以保持Cookies
            session = requests.Session()
            
            # 下载文件
            print(f"尝试下载文件: {modified_link}")
            response = session.get(modified_link, headers=headers, stream=True)
            response.raise_for_status()  # 确保请求成功
            
            # 如果响应头中有文件名，使用该文件名
            if 'content-disposition' in response.headers:
                cd = response.headers['content-disposition']
                if 'filename=' in cd:
                    filename = re.findall('filename="(.+)"', cd)
                    if filename:
                        original_filename = filename[0]
            
            # 构建保存路径
            save_path = os.path.join(SAVE_DIR, original_filename)
            
            # 保存文件
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
            
            print(f"文件已保存到: {save_path}")
            return jsonify({
                "status": "success", 
                "message": "链接已接收，文件已下载", 
                "saved_to": save_path
            }), 200
        except Exception as e:
            print(f"下载文件时出错: {str(e)}")
            return jsonify({
                "status": "error", 
                "message": f"下载文件时出错: {str(e)}"
            }), 500
    else:
        return jsonify({
            "status": "error", 
            "message": "未接收到有效链接"
        }), 400

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
